package de.datenwalze.winterpokal;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.LinearLayout;
import android.widget.TextView;
import de.datenwalze.winterpokal.http.WPHttpConnection;
import de.datenwalze.winterpokal.json.WPJsonResponse;
import de.datenwalze.winterpokal.json.WPUser;

public class TeamActivity extends Activity {

	public static final int MAX_USERS = 5;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.team);

		runHttpRequestAndFillView();
	}

	private void runHttpRequestAndFillView() {
		
		WPJsonResponse wpJsonResponse = WPHttpConnection.getHttpResult();

		((TextView) findViewById(R.id.teamNameValue)).setText(wpJsonResponse
				.getData().getTeam().getName());
		((TextView) findViewById(R.id.teamLeaderValue)).setText(wpJsonResponse
				.getData().getTeam().getLeader().getName());

		ViewGroup teamUsers = (ViewGroup) findViewById(R.id.teamUsers);
		
		// Add a user.xml for every single user
		for (int i = 0; i < wpJsonResponse.getData().getUsers().length; i++) {
			
			WPUser wpUser = wpJsonResponse.getData().getUsers()[i];
			inflateAndAddUser(teamUsers, wpUser);
		}

	}
	
	/**
	 * This will inflate a <code>user.xml</code> file and add it to the
	 * given <code>ViewGroup</code>. 
	 * 
	 * @param teamUsers
	 * @param wpUser
	 */
	private void inflateAndAddUser(ViewGroup teamUsers, WPUser wpUser) {
		View teamUser = LayoutInflater.from(this).inflate(R.layout.user,
				teamUsers, false);
		
		((TextView) teamUser.findViewById(R.id.userName))
				.setText(wpUser.getName());
		((TextView) teamUser.findViewById(R.id.userDuration))
				.setText(Integer.toString(wpUser.getDuration()));
		((TextView) teamUser.findViewById(R.id.userEntries))
				.setText(Integer.toString(wpUser.getEntries()));
		((TextView) teamUser.findViewById(R.id.userPoints)).setText(Integer
				.toString(wpUser.getPoints()));
		
		teamUsers.addView(teamUser);

		View divider = LayoutInflater.from(this).inflate(R.layout.divider,
				teamUsers, false);

		teamUsers.addView(divider);
	}
}
